﻿using MiniFox.Components;
using MiniFox.Configurations;
using MiniFox.Platform.OAuth2.Configurations;
using MiniFox.Platform.OAuth2.Providers;
using System.ComponentModel.DataAnnotations;

namespace MiniFox.Platform.OAuth2.Models
{
    /// <summary>
    /// 
    /// </summary>
    public class SecureStringAttribute : ValidationAttribute
    {
        readonly SecureStringType _type;
        /// <summary>
        /// 
        /// </summary>
        public SecureStringAttribute(SecureStringType type)
        {
            _type = type;
        }

        /// <summary>
        /// 
        /// </summary>
        public SecureStringType CurrentSecureStringType
        {
            get { return _type; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            var provider = ComponentFactory.GetComponent<IOAuth2ConfigProvider>();
            var config = provider.PassportConfiguration;

            string str = value == null ? string.Empty : value.ToString();

            bool isValid = false;
            switch (this.CurrentSecureStringType)
            {
                case SecureStringType.LoginName:
                    isValid = !config.EnableLoginNameSignin || config.LoginNameRegex.IsMatch(str);
                    break;
                case SecureStringType.Cellphone:
                    isValid = !config.EnableCellphoneSignin || config.CellphoneRegex.IsMatch(str);
                    break;
                case SecureStringType.Email:
                    isValid = !config.EnableRegEmailSignin || config.EmailRegex.IsMatch(str);
                    break;
                case SecureStringType.Password:
                    isValid = config.PasswordRegex.IsMatch(str);
                    break;
            }
            
            return isValid;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public enum SecureStringType
    {
        /// <summary>
        /// 
        /// </summary>
        LoginName,
        /// <summary>
        /// 
        /// </summary>
        Email,
        /// <summary>
        /// 
        /// </summary>
        Cellphone,
        /// <summary>
        /// 
        /// </summary>
        Password
    }
}
